package cdc.retrofit.official.crawler;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import okhttp3.ResponseBody;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class PageAdapter implements Converter<ResponseBody, Page> {
	static final Converter.Factory FACTORY = new Converter.Factory() {
		@Override
		public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
				Retrofit retrofit) {
			if (type == Page.class)
				return new PageAdapter();
			return null;
		}
	};

	@Override
	public Page convert(ResponseBody responseBody) throws IOException {
		Document document = Jsoup.parse(responseBody.string());
		List<String> links = new ArrayList<>();
		for (Element element : document.select("a[href]")) {
			links.add(element.attr("href"));
		}
		return new Page(document.title(), Collections.unmodifiableList(links));
	}

}
